package com.garfield.service;


import com.garfield.dao.UserDAO;
import com.garfield.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDAO userDAO;

    @Override
    public void register(User user) {
        //根据用户名判断用户是否已存在
        User oldUser = userDAO.findByUserName(user.getUsername());
        if(oldUser == null){
            //生成用户状态
            user.setStatus("已激活");
            //设置用户注册时间
            user.setRegisterTime(new Date());
            //调用dao
            userDAO.save(user);
        }else{
            throw new RuntimeException("用户已存在！");
        }
    }

    @Override
    public User login(User user){
        //根据用户名查询是否存在该用户
        User userDB = userDAO.findByUserName(user.getUsername());
        if(userDB != null){
            //比较密码
            if(userDB.getPassword().equals(user.getPassword())){
                return userDB;
            }else{
                throw new RuntimeException("密码错误！");
            }
        }else{
            throw new RuntimeException("用户名错误！");
        }
    }
}
